package SlidingWindow.Medium;

public class LC0003 {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() <= 1) return s.length();

        char[] charArray = s.toCharArray();
        boolean[] appearance = new boolean[128];
        int left = 0, right = 1;
        appearance[charArray[left]] = true;
        int maxLength = 1, length = 1;
        while (right < s.length()) {
            length++;
            if (!appearance[charArray[right]]) {
                maxLength = Math.max(maxLength, length);
                appearance[charArray[right]] = true;
                right++;
            }
            else { // 出现重复字符
                while (charArray[left] != charArray[right]) {
                    appearance[charArray[left]] = false;
                    left++;
                    length--;
                }
                // 此时left一定指向重复的字符
                left++;
                length--;
                right++; // right始终指向下一个需要考察的字符
                maxLength = Math.max(length, maxLength);
            }
        }

        return maxLength;
    }
}
